package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Override
    public Cart addCart(Cart cart) {
        //添加之前首先判断是该用户id下是否存在该菜
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        wrapper.eq(cart.getDishId() != null,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId() != null,Cart::getSetmealId,cart.getSetmealId());
        Cart cart1 = cartMapper.selectOne(wrapper);
        if (cart1 != null){
            //如果存在的话，更新一下份数即可
            cart1.setNumber(cart1.getNumber()+1);
            cartMapper.updateById(cart1);
        }else {
            //如果数据表中没有
            //设置菜的用户id
            cart.setUserId(UserHolder.get().getId());
            //设置菜的份数
            cart.setNumber(1);
            //设置创建时间
            cart.setCreateTime(new Date());
            //保存
            cartMapper.insert(cart);
        }
        return cart;
    }

    @Override
    public List<Cart> findCartList() {
        //通过userid进行筛选
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        wrapper.orderByDesc(Cart::getCreateTime);
        List<Cart> cartList = cartMapper.selectList(wrapper);
        return cartList;
    }

    @Override
    public Cart sub(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        wrapper.eq(cart.getDishId() != null ,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId() != null , Cart::getSetmealId,cart.getSetmealId());
        Cart cart1 = cartMapper.selectOne(wrapper);
        if(cart1.getNumber() > 1){
            //删除
            cart1.setNumber(cart1.getNumber()-1);
            cartMapper.updateById(cart1);
        }else {
            cartMapper.deleteById(cart1);
            cart1.setNumber(0);
        }
        return cart1;
    }

    @Override
    public void cleanCart() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());//user_id = ?
        cartMapper.delete(wrapper);
    }

}
